//
//  LoginManager.m
//  WOFishingBoat
//
//  Created by 郑逸凯 on 2019/1/8.
//  Copyright © 2019年 郑逸凯. All rights reserved.
//

#import "LoginManager.h"
#import "YAUserDefault.h"

@interface LoginManager ()
@property (nonatomic,strong)RequestSession *loginRequestSession;
@end

@implementation LoginManager

+ (instancetype)sharedInstance {
    static LoginManager *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 要使用self来调用
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}


- (BOOL)hadAccountInfo {
    NSString *account = [YAUserDefault ya_objectForKey:KEY_ACCOUNT];
    NSString *pswd =  [YAUserDefault ya_objectForKey:KEY_PSWD];
    if ([NSString tm_emptyString:account]) {
        return NO;
    }
    if ([NSString tm_emptyString:pswd]) {
        return NO;
    }
    return YES;
}

- (void)LoginWithDefaultAccountCompletionHandler:(void (^)(id , NSError * ))completionHandler {
    if (![self hadAccountInfo]) {
        if (completionHandler) {
            completionHandler(nil,[NSError errorWithDomain:@"账户或密码不存在" code:-1 userInfo:nil]);
        }
    }else {
        NSString *account = [YAUserDefault ya_objectForKey:KEY_ACCOUNT];
        NSString *pswd =  [YAUserDefault ya_objectForKey:KEY_PSWD];
        [self LoginWithAccount:account pswd:pswd completionHandler:completionHandler];
    }
}

- (void)LoginWithAccount:(NSString *)account pswd:(NSString *)pswd completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler {
    NSString *urlStr = [NSString stringWithFormat:WO_PATH_LOGIN,account,pswd];
   
    //    @weakify(self);
    [self.loginRequestSession getWithURLString:WO_URL(urlStr) parameters:nil completionHandler:^(id responseObject, NSError *error) {
        if (!error) {
            [YAUserDefault ya_setObject:account forKey:KEY_ACCOUNT];
            [YAUserDefault ya_setObject:pswd forKey:KEY_PSWD];
            [[NSNotificationCenter defaultCenter] postNotificationName:WOLoginSuccessNotification object:nil];
        }
        if (completionHandler) {
            completionHandler(responseObject,error);
        }
    }];
}


- (RequestSession *)loginRequestSession {
    if (!_loginRequestSession) {
        _loginRequestSession = [[RequestSession alloc] init];
    }
    return _loginRequestSession;
}
@end
